<template>
    <el-dialog :model-value="modelValue" :title="dialogTitle" width="30%" @close="handleClose">
        <el-form ref="formRef" :model="form" label-width="100px">

            <el-tree ref="treeRef" :data="treeData" :props="defaultProps" show-checkbox :default-expand-all=true
                node-key="id" :check-strictly=true />


        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="handleConfirm">确认</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>
    
<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil, { getServerUrl } from "@/util/request";
import { ElMessage } from 'element-plus';

const defaultProps = {
    children: 'children',
    label: 'name'
}

const props = defineProps({
    id: {
        type: Number,
        default: -1,
        required: true
    },
    dialogTitle: {
        type: String,
        default: ()=>{ return '分配权限'},
        required: false
    },
    modelValue: {
        type: Boolean,
        default: false,
        required: true
    }
});

const form = ref({
    id: -1
})

const treeData = ref([]);

const treeRef = ref(null);


const initFormData = async (id) => {
    // 查询所有菜单权限
    const result = await requestUtil.get('/sys/menu/treeList');
    let data = result.data;
    treeData.value = data.result;
    form.value.id = id;
    // 查询拥有的菜单权限
    const checkedResult = await requestUtil.get('/sys/role/menus/'+id);
    let checkedData = checkedResult.data;
    treeRef.value.setCheckedKeys(checkedData.result);
}

watch(() => props.modelValue, () => {
    let id = props.id;
    if (id != -1) {

        initFormData(id);
    }
})

// 关闭弹窗
const emits = defineEmits(['update:modelValue', 'initRoleList']);

const handleClose = () => {
    emits('update:modelValue', false);
}

// 提交表单
const formRef = ref(null);
const handleConfirm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let menuIdList = treeRef.value.getCheckedKeys();
            const result = await requestUtil.post('/sys/role/updateMenus/' + form.value.id, menuIdList);
            let data = result.data;
            if (data.code == 2000) {
                ElMessage.success("执行成功！")
                emits("initRoleList")
                handleClose();
            } else {
                ElMessage.error(data.msg);
            }
        }

    })
}


</script>


<style lang="scss" scoped>

</style>